//webSocket通用处理
import store from "../../store"

export const webSocketMixins = {
  data() {
    return {
      sendType: "",
      webSocket: null,
      lockReconnect: false,
      timeoutNum: null,//断开 重连倒计时
      timeout: 50 * 1000,//30秒一次心跳
      timeoutObj: null,//心跳心跳倒计时
      serverTimeoutObj: null,//心跳倒计时
      lastRunTime: Date.now(),//上次播放声音的时间,
      onMessage: null
    }
  },
  props: {},

  methods: {
    initWebSocket(onMessage, sendType) {
      let userId = store.getters.userId
      let url = this.api.websocket + sendType
      if (userId) {
        url = this.api.websocket+"/" + userId + "/" + sendType
      }
      url = url.replace("https", "ws").replace("http", "ws")
      this.webSocket = new WebSocket(url)
      this.webSocket.onopen = this.websocketOnopen
      this.webSocket.onerror = this.websocketOnerror
      this.webSocket.onmessage = this.websocketOnmessage
      this.webSocket.onclose = this.websocketOnclose
      this.onMessage = onMessage
      this.sendType = sendType
    },
    websocketOnopen: function() {
      console.log("WebSocket连接成功")
      //开启心跳
      this.start()
    },
    websocketOnerror: function(e) {
      console.log("WebSocket连接发生错误")
      this.reconnect()
    },
    websocketOnmessage: function(e) {
      let messageInfo = JSON.parse(e.data)
      if (messageInfo) {
        console.info("websocketOnmessage",messageInfo)
        //收到服务器信息，心跳重置
        this.reset()
      }
      if (messageInfo && !messageInfo.code) {
        console.info("onMessage:", messageInfo)
        this.onMessage && this.onMessage(messageInfo)
      }
    },
    websocketOnclose: function(e) {
      console.log("connection closed (" + e + ")")
      if (e) {
        console.log("connection closed (" + e.code + ")")
      }
      this.reconnect()
    },
    websocketSend(text) { // 数据发送
      try {
        this.webSocket.send(text)
      } catch (err) {
        console.log("send failed (" + err.code + ")")
      }
    },
    /**
     * 开启心跳
     */
    start() {
      console.info("开启心跳")
      this.timeoutObj && clearTimeout(this.timeoutObj)
      this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
      this.timeoutObj = setTimeout(() => {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (this.webSocket.readyState == 1) {
          console.info("发送心跳信息")
          //如果连接正常
          this.webSocket.send("{\"message\":\"1\",\"code\":\"1\"}")
        } else {//否则重连
          this.reconnect()
        }
        this.serverTimeoutObj = setTimeout(() => {
          console.info("超时关闭")
          //超时关闭
          this.webSocket.close()
        }, this.timeout)

      }, this.timeout)
    },
    /**
     * 重置心跳
     */
    reset() {
      //清除时间
      clearTimeout(this.timeoutObj)
      clearTimeout(this.serverTimeoutObj)
      //重启心跳
      this.start()
    },
    reconnect() {
      if (this.lockReconnect) {
        return
      }
      this.lockReconnect = true
      //没连接上会一直重连，设置延迟避免请求过多
      this.timeoutNum && clearTimeout(this.timeoutNum)
      this.timeoutNum = setTimeout(() => {
        //新连接
        this.initWebSocket(this.onMessage, this.sendType)
        this.lockReconnect = false
      }, 5000)
    }
  }
}
